package me.maiz.babyisland.web;

import me.maiz.babyisland.web.form.LoginForm;
import lombok.extern.slf4j.Slf4j;
import me.maiz.babyisland.web.form.LoginForm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Slf4j
@Controller
public class LoginController extends BaseController {


    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String toLogin(){
        return "login";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String doLogin(LoginForm form, ModelMap modelMap){
        String message = null;
        UsernamePasswordToken token = new UsernamePasswordToken(form.getUsername(),form.getPassword());
        token.setRememberMe(false);

        Subject currUser = SecurityUtils.getSubject();
            try {
                currUser.login(token);
                return "redirect:/home";
            }catch (IncorrectCredentialsException e){
                log.info("用户名或者密码错误");
                message="用户名或者密码错误";
            }catch (AuthenticationException e){
                log.warn("登录失败",e);
                message="登录失败";
            }
        modelMap.addAttribute("message",message);

        return "login";
    }


}
